package junior.util.aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

public class ProxyMethodInterceptor implements MethodInterceptor, InitializingBean {
	private static Logger logger = LoggerFactory.getLogger(ProxyMethodInterceptor.class);
	
	private String includeAntPattern;
	private MethodInterceptor proxyInterceptor;
	
	private PathMatcher pathMatcher = new AntPathMatcher();
	private String[] includes = new String[0];

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(proxyInterceptor, "Property 'proxyInterceptor' is required");
		
		if (StringUtils.hasText(includeAntPattern)) {
			String[] items = includeAntPattern.trim().split("[,]");
			includes = new String[items.length];
			int idx = 0;
			for (String item : items) {
				includes[idx ++] = item.trim();
			}
		}
	}

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		String name = invocation.getThis().getClass().getName() + "." + invocation.getMethod().getName();
		for (String include : includes) {
			if (pathMatcher.match(include, name)) {
				logger.debug("matched : {} : {}", include, name);
				return proxyInterceptor.invoke(invocation);
			}
		}
		
		return invocation.proceed();
	}

	public String getIncludeAntPattern() {
		return includeAntPattern;
	}
	public void setIncludeAntPattern(String includeAntPattern) {
		this.includeAntPattern = includeAntPattern;
	}
	public MethodInterceptor getProxyInterceptor() {
		return proxyInterceptor;
	}
	public void setProxyInterceptor(MethodInterceptor proxyInterceptor) {
		this.proxyInterceptor = proxyInterceptor;
	}
}
